package me.cloudcat.develop.controller;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import me.cloudcat.develop.dao.configuration.UserDao;
import me.cloudcat.develop.entity.configuration.User;


@RequestMapping("/cache")
@Controller
public class HibernateCacheController {
	private static Logger logger = Logger.getLogger(HibernateCacheController.class);

	@Autowired
	EntityManagerFactory factory;

	@Autowired
	UserDao userDao;

	@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
	public String log() {
		logger.info("测试日志log4j");
		logger.debug("测试日志log4j");
		logger.error("测试日志log4j");
		return "/index";
	}

	/**
	 * 测试一级缓存
	 * @return
	 */
	@RequestMapping(value = "/testLevelOneJPA", method = { RequestMethod.GET, RequestMethod.POST })
	public String testJPA() {
		EntityManager manager = factory.createEntityManager();
		User user = (User) manager.find(User.class, 1L);
		System.out.println(user.getUsername());
//
//		EntityManager manager2 = factory.createEntityManager();
		//此处会从一级缓存中取数据
		User user2 = (User) manager.find(User.class, 1L);
		System.out.println(user2.getUsername());
		return "/index";

	}

	/**
	 * 测试二级缓存（createQuery）
	 * @return
	 */
	@RequestMapping(value = "/testLevelTwoCache", method = { RequestMethod.GET, RequestMethod.POST })
	public String testCache() {
		EntityManager manager = factory.createEntityManager();
		Query query = manager.createQuery("from User");
		//设置query从二级缓存中取数据
		query.setHint("org.hibernate.cacheable", true);
		List resultList = query.getResultList();
		//此处会调用二级缓存
		List resultList2 = query.getResultList();
		System.out.println(resultList.size());
		
		//下列代码会从二级缓存中取数据
		EntityManager manager2 = factory.createEntityManager();
		Query query2 = manager2.createQuery("from User");
		query2.setHint("org.hibernate.cacheable", true);
		resultList = query2.getResultList();
		System.out.println(resultList.size());
		
		return "/index";

	}
	
	/**
	 * 测试二级缓存（jpa方法）
	 * @return
	 */
	@RequestMapping(value = "/testJPALevelTwoCache", method = { RequestMethod.GET, RequestMethod.POST })
	public String testJPALevelTwoCache() {

		List<User> list = userDao.findAllUser();
		System.out.println(list.size());

		list = userDao.findAllUser();
		System.out.println(list.size());
		return "/index";

	}
}
